"""
第三阶段配置管理类
"""

import os
from typing import Dict, List, Optional, Any
from dataclasses import dataclass, field
from pathlib import Path


@dataclass
class APIConfig:
    """API配置"""
    base_url: str = "https://api.siliconflow.cn/v1/chat/completions"
    api_key: str = "sk-umjpwhgrwtwcrifwfrczofcfeprfvhhcrvvpnbhkwrkvjnux"
    text_model: str = "Qwen/Qwen2.5-7B-Instruct"
    vision_model: str = "THUDM/GLM-4.1V-9B-Thinking"  # 修复：使用与vision.py一致的模型名称
    timeout: int = 180  # 优化超时时间到3分钟
    max_retries: int = 3  # 减少重试次数避免过长等待


@dataclass
class AgentConfig:
    """代理配置"""
    max_parallel_agents: int = 5
    agent_timeout: int = 300  # 优化代理超时时间到5分钟
    enable_parallel_processing: bool = True
    
    # 各代理的权重配置
    agent_weights: Dict[str, float] = field(default_factory=lambda: {
        "format_agent": 0.1,
        "compliance_agent": 0.2,
        "logic_agent": 0.15,
        "content_agent": 0.25,
        "traffic_agent": 0.1,
        "infrastructure_agent": 0.1,
        "environment_agent": 0.05,
        "vision_agent": 0.05
    })
    
    @property
    def enable_parallel(self) -> bool:
        """兼容性属性，返回enable_parallel_processing的值"""
        return self.enable_parallel_processing
    
    def to_dict(self) -> Dict[str, Any]:
        """转换为字典"""
        return {
            'max_parallel_agents': self.max_parallel_agents,
            'agent_timeout': self.agent_timeout,
            'enable_parallel_processing': self.enable_parallel_processing,
            'agent_weights': self.agent_weights.copy()
        }
    
    def get_agent_weight(self, agent_name: str) -> float:
        """获取代理权重"""
        # 标准化代理名称
        normalized_name = agent_name.lower()
        if not normalized_name.endswith('_agent'):
            normalized_name += '_agent'
        
        return self.agent_weights.get(normalized_name, 0.1)


@dataclass
class RetrievalConfig:
    """检索配置"""
    max_results: int = 10
    similarity_threshold: float = 0.7
    enable_reranking: bool = True
    chunk_size: int = 1000


@dataclass
class ProcessingConfig:
    """处理配置"""
    batch_size: int = 10
    max_workers: int = 4
    enable_caching: bool = True
    cache_ttl: int = 3600  # 缓存时间（秒）


@dataclass
class Stage3Config:
    """第三阶段总配置"""
    api: APIConfig = field(default_factory=APIConfig)
    agent: AgentConfig = field(default_factory=AgentConfig)
    retrieval: RetrievalConfig = field(default_factory=RetrievalConfig)
    processing: ProcessingConfig = field(default_factory=ProcessingConfig)
    
    # 存储路径
    storage_path: str = "storage"
    
    # 输出配置
    output_format: str = "json"
    enable_detailed_logging: bool = True
    log_level: str = "INFO"
    
    # 审查规则文件路径
    rules_file: Optional[str] = None
    
    @classmethod
    def from_env(cls) -> 'Stage3Config':
        """从环境变量创建配置"""
        config = cls()
        
        # API配置
        if os.getenv('SILICONFLOW_API_KEY'):
            config.api.api_key = os.getenv('SILICONFLOW_API_KEY')
        
        if os.getenv('SILICONFLOW_BASE_URL'):
            config.api.base_url = os.getenv('SILICONFLOW_BASE_URL')
            
        # 其他配置
        if os.getenv('MAX_PARALLEL_AGENTS'):
            config.agent.max_parallel_agents = int(os.getenv('MAX_PARALLEL_AGENTS'))
            
        if os.getenv('LOG_LEVEL'):
            config.log_level = os.getenv('LOG_LEVEL')
            
        return config
    
    @classmethod
    def from_dict(cls, config_dict: Dict[str, Any]) -> 'Stage3Config':
        """从字典创建配置"""
        config = cls()
        
        # 处理API配置
        if 'api_key' in config_dict:
            config.api.api_key = config_dict['api_key']
        if 'base_url' in config_dict:
            config.api.base_url = config_dict['base_url']
        if 'text_model' in config_dict:
            config.api.text_model = config_dict['text_model']
        if 'vision_model' in config_dict:
            config.api.vision_model = config_dict['vision_model']
            
        # 处理代理配置
        if 'max_parallel_agents' in config_dict:
            config.agent.max_parallel_agents = config_dict['max_parallel_agents']
        if 'enable_parallel_processing' in config_dict:
            config.agent.enable_parallel_processing = config_dict['enable_parallel_processing']
            
        # 处理其他配置
        if 'storage_path' in config_dict:
            config.storage_path = config_dict['storage_path']
        if 'output_format' in config_dict:
            config.output_format = config_dict['output_format']
        if 'log_level' in config_dict:
            config.log_level = config_dict['log_level']
        if 'rules_file' in config_dict:
            config.rules_file = config_dict['rules_file']
            
        return config
    
    def validate(self) -> bool:
        """验证配置"""
        if not self.api.api_key:
            raise ValueError("API密钥不能为空")
            
        if not self.api.base_url:
            raise ValueError("API基础URL不能为空")
            
        if self.agent.max_parallel_agents <= 0:
            raise ValueError("并行代理数量必须大于0")
            
        return True


# 默认配置实例
default_config = Stage3Config()